package cn.trigram.excel;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.jxls.common.Context;
import org.jxls.formula.FastFormulaProcessor;
import org.jxls.transform.Transformer;
import org.jxls.transform.poi.PoiTransformer;
import org.jxls.util.JxlsHelper;

public class ExcelWriter {

  private final String templateFilePath;

  private final File out;

  /**
   * 是否使用快速公式处理，默认是快速公式处理。<br/>
   * 快速公式处理可处理90%的简单导出。<br/>
   *
   * @see FastFormulaProcessor, StandardFormulaProcessor
   */
  private boolean useFastFormulaProcessor = false;

  /**
   * 是否计算公式，在测试中可以开启用于验证公式
   */
  private boolean evaluateFormulas = false;

  private boolean fullFormulaRecalculationOnOpening = false;

  public ExcelWriter(final String templateFilePath, final File out, boolean useFastFormulaProcessor,
      boolean evaluateFormulas, boolean fullFormulaRecalculationOnOpening) {

    this.templateFilePath = templateFilePath;
    this.out = out;
    this.useFastFormulaProcessor = useFastFormulaProcessor;
    this.evaluateFormulas = evaluateFormulas;
    this.fullFormulaRecalculationOnOpening = fullFormulaRecalculationOnOpening;
  }

  public void write(final Context context) throws IOException {

    write(context, transformer -> transformer);
  }

  public void write(final Context context, TransformerProcessor transformerProcessor)
      throws IOException {

    ClassLoader ctLoader = Thread.currentThread().getContextClassLoader();
    try (InputStream is = ctLoader.getResourceAsStream(this.templateFilePath)) {
      try (OutputStream fos = new FileOutputStream(this.out)) {
        Transformer transformer = PoiTransformer.createTransformer(is, fos);
        transformer = transformerProcessor.processor(transformer);
        JxlsHelper jxls = JxlsHelper.getInstance();
        if (this.useFastFormulaProcessor) {
          jxls.setUseFastFormulaProcessor(this.useFastFormulaProcessor);
        }
        jxls.setEvaluateFormulas(this.evaluateFormulas);
        jxls.setFullFormulaRecalculationOnOpening(this.fullFormulaRecalculationOnOpening);
        jxls.processTemplate(context, transformer);
      }
    } catch (IOException e) {
      throw e;
    }
  }

}
